package cn.xspace.wnx.util;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.xspace.android.xafcommon.appliction.BaseApplication;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;

import java.util.ArrayList;
import java.util.List;

import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.listener.HxMessageListener;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatActivity;
import cn.xspace.wnx.activity.NoticeOrWNXListActivity;
import cn.xspace.wnx.activity.WnxOrgMessageListActivity;
import cn.xspace.wnx.broadreceiver.CallReceiver;
import cn.xspace.wnx.db.WNXDBManager;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class HuanXinHelper {
    public static String password_temp = "02ce3adfe27b737ea466b83f3a240db6";

    /**
     * data sync listener
     */
    public interface DataSyncListener {
        /**
         * sync complete
         *
         * @param success true：data sync successful，false: failed to sync data
         */
        void onSyncComplete(boolean success);
    }

    protected static final String TAG = "HuanXinHelper";

//    private EaseUI easeUI;

    /**
     * EMEventListener
     */
    protected EMMessageListener messageListener = null;

//    private Map<String, EaseUser> contactList;

//    private Map<String, RobotUser> robotList;

//    private UserProfileManager userProManager;

    private static HuanXinHelper instance = null;

//    private DemoModel demoModel = null;

    /**
     * sync groups status listener
     */
    private List<DataSyncListener> syncGroupsListeners;
    /**
     * sync contacts status listener
     */
    private List<DataSyncListener> syncContactsListeners;
    /**
     * sync blacklist status listener
     */
    private List<DataSyncListener> syncBlackListListeners;

    private boolean isSyncingGroupsWithServer = false;
    private boolean isSyncingContactsWithServer = false;
    private boolean isSyncingBlackListWithServer = false;
    private boolean isGroupsSyncedWithServer = false;
    private boolean isContactsSyncedWithServer = false;
    private boolean isBlackListSyncedWithServer = false;

    public boolean isVoiceCalling;
    public boolean isVideoCalling;

    private String username;

    private Context appContext;

    private CallReceiver callReceiver;

//    private InviteMessgeDao inviteMessgeDao;
//    private UserDao userDao;


//    private boolean isGroupAndContactListenerRegisted;
//    private EaseSettingsProvider easeSettingsProvider;

    private HuanXinHelper() {

    }

    public synchronized static HuanXinHelper getInstance() {
        if (instance == null) {
            instance = new HuanXinHelper();
        }
        return instance;
    }

//    public EaseSettingsProvider getSettingsProvider() {
//        return easeSettingsProvider;
//    }


    /**
     * init helper
     *
     */
    public void init() {

//        demoModel = new DemoModel(context);
        EMOptions options = initChatOptions();
        //use default options if options is null
//        if (EaseUI.getInstance().init(context, options)) {
        appContext = BaseApplication.mInstance;
        EMClient.getInstance().init(appContext, options);
        //debug mode, you'd better set it to false, if you want release your App officially.
        EMClient.getInstance().setDebugMode(true);

        Notifier.getInstance().init(appContext);
        //get easeui instance
//            easeUI = EaseUI.getInstance();
        //to set user's profile and avatar
        setEaseUIProviders();
        //initialize preference manager
//            PreferenceManager.init(context);
        //initialize profile manager
//            getUserProfileManager().init(context);

//            EMClient.getInstance().callManager().getVideoCallHelper().setAdaptiveVideoFlag(getModel()
// .isAdaptiveVideoEncode());

        setGlobalListeners();
//        initDbDao();
//        }
    }

    private void setEaseUIProviders() {
        Notifier.getInstance().setNotificationInfoProvider(new Notifier.EaseNotificationInfoProvider() {
            @Override
            public String getDisplayedText(MessageEntity message) {
                return null;
            }

            @Override
            public String getLatestText(MessageEntity message, int fromUsersNum, int messageNum) {
                return null;
            }

            @Override
            public String getTitle(MessageEntity message) {
                return null;
            }

            @Override
            public int getSmallIcon(MessageEntity message) {
                return 0;
            }

            @Override
            public Intent getLaunchIntent(MessageEntity message) {
                Intent intent = null;

                if (message.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
                    //单聊
                    intent = new Intent(appContext, ChatActivity.class);
                    Bundle dataBundle = new Bundle();
                    dataBundle.putString(BldNavigation.SENDER_ID, message.msg_sender_id);
                    dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_SINGLE.toNumber());
                    dataBundle.putString(BldNavigation.CHAT_NAME, message.msg_sender_name);
                    dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, message.msg_logo);
                    intent.putExtra(BldNavigation.KEY_BUNDLER, dataBundle);
                } else if (message.msg_type == MsgType.CHAT_CROUP.toNumber()) {
                    //群聊
                    intent = new Intent(appContext, ChatActivity.class);
                    Bundle dataBundle = new Bundle();
                    dataBundle.putString(BldNavigation.SENDER_ID, message.msg_group_id);
                    dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_CROUP.toNumber());
                    dataBundle.putString(BldNavigation.CHAT_NAME, message.msg_group_name);
                    dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, message.msg_logo);
                    intent.putExtra(BldNavigation.KEY_BUNDLER, dataBundle);
                } else if (message.msg_type == MsgType.WNX_MSG.toNumber()) {
                    LogUtil.d(TAG, "跳转页面");
                    Bundle dataBundle = new Bundle();
                    dataBundle.putString(BldNavigation.SENDER_ID, message.msg_sender_id);
                    dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.WNX_MSG.toNumber());
                    dataBundle.putString(BldNavigation.SENDER_NAME, message.msg_sender_name);
                    //跳转页面
                    intent = new Intent(appContext, WnxOrgMessageListActivity.class);
                    intent.putExtra(BldNavigation.KEY_BUNDLER, dataBundle);

                } else if (message.msg_type == MsgType.NOTICE.toNumber()) {
                    LogUtil.d(TAG, "跳转页面");
//                    Bundle dataBundle = new Bundle();
//                    dataBundle.putString(Navigator.SENDER_ID, message.msg_sender_id);
//                    dataBundle.putInt(Navigator.CHAT_TYPE, MessageEntity.MsgType.NOTICE.toNumber());
//                    dataBundle.putString(Navigator.SENDER_NAME, message.msg_sender_name);
                    //跳转页面
                    intent = new Intent(appContext, NoticeOrWNXListActivity.class);
                    intent.putExtra("MessageEntity", message);
                } else if (message.msg_type == MsgType.CHAT_QAC_FORM.toNumber()) {
                    //表单相关
                    intent = new Intent(appContext, ChatActivity.class);
                    Bundle dataBundle = new Bundle();
                    dataBundle.putString(BldNavigation.SENDER_ID, message.msg_sender_id);
                    dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_QAC_FORM.toNumber());
                    dataBundle.putString(BldNavigation.CHAT_NAME, message.msg_sender_name);
                    dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, message.msg_logo);
                    dataBundle.putInt(BldNavigation.FormType, message.form_type);
                    dataBundle.putString(BldNavigation.FormId, message.form_id);
                    dataBundle.putString(BldNavigation.FormName, message.form_name);
                    dataBundle.putString(BldNavigation.FormUrl, message.form_url);
//                    dataBundle.putBoolean(BldNavigation.FormCanTAlk, true);

                    if (!"1".equals(MyInfoUtil.getIsFarmer())) {
                        if (message.form_status == Type.WorkItemOperateStatus.UN_OPERATE || message.form_status ==
                                Type.WorkItemOperateStatus.OUT_TIME) {
                            dataBundle.putBoolean(BldNavigation.FormCanTAlk, true);
                        } else {
                            dataBundle.putBoolean(BldNavigation.FormCanTAlk, false);
                        }
                    }
                    intent.putExtra(BldNavigation.KEY_BUNDLER, dataBundle);
                }
                return intent;
            }
        });
    }


    private EMOptions initChatOptions() {
        Log.d(TAG, "init HuanXin Options");

        EMOptions options = new EMOptions();
        // set if accept the invitation automatically 设置是否自动接收好友邀请
        options.setAcceptInvitationAlways(false);
        //设置是否自动加入群组
        options.setAutoAcceptGroupInvitation(true);
        // set if you need read ack
        options.setRequireAck(true);
        // set if you need delivery ack
        options.setRequireDeliveryAck(false);

        //you need apply & set your own id if you want to use google cloud messaging.
//        options.setGCMNumber("324169311137");
        //you need apply & set your own id if you want to use Mi push notification
//        options.setMipushConfig("2882303761517426801", "5381742660801");
        //you need apply & set your own id if you want to use Huawei push notification
//        options.setHuaweiPushAppId("10492024");

        //set custom servers, commonly used in private deployment
//        if(demoModel.isCustomServerEnable() && demoModel.getRestServer() != null && demoModel.getIMServer() != null) {
//            options.setRestServer(demoModel.getRestServer());
//            options.setIMServer(demoModel.getIMServer());
//            if(demoModel.getIMServer().contains(":")) {
//                options.setIMServer(demoModel.getIMServer().split(":")[0]);
//                options.setImPort(Integer.valueOf(demoModel.getIMServer().split(":")[1]));
//            }
//        }
//
//        options.allowChatroomOwnerLeave(getModel().isChatroomOwnerLeaveAllowed());
//        options.setDeleteMessagesAsExitGroup(getModel().isDeleteMessagesAsExitGroup());
//        options.setAutoAcceptGroupInvitation(getModel().isAutoAcceptGroupInvitation());

        return options;
    }

//    protected void setEaseUIProviders() {
//        // set profile provider if you want easeUI to handle avatar and nickname
////        easeUI.setUserProfileProvider(new EaseUserProfileProvider() {
////
////            @Override
////            public EaseUser getUser(String username) {
////                return getUserInfo(username);
////            }
////        });
//
//        //set options
//        easeUI.setSettingsProvider(new EaseSettingsProvider() {
//
//            @Override
//            public boolean isSpeakerOpened() {
//                return demoModel.getSettingMsgSpeaker();
//            }
//
//            @Override
//            public boolean isMsgVibrateAllowed(EMMessage message) {
//                return demoModel.getSettingMsgVibrate();
//            }
//
//            @Override
//            public boolean isMsgSoundAllowed(EMMessage message) {
//                return demoModel.getSettingMsgSound();
//            }
//
//            @Override
//            public boolean isMsgNotifyAllowed(EMMessage message) {
//                if(message == null){
//                    return demoModel.getSettingMsgNotification();
//                }
//                if(!demoModel.getSettingMsgNotification()){
//                    return false;
//                }else{
//                    String chatUsename = null;
//                    List<String> notNotifyIds = null;
//                    // get user or group id which was blocked to show message notifications
//                    if (message.getChatType() == EMMessage.ChatType.Chat) {
//                        chatUsename = message.getFrom();
//                        notNotifyIds = demoModel.getDisabledIds();
//                    } else {
//                        chatUsename = message.getTo();
//                        notNotifyIds = demoModel.getDisabledGroups();
//                    }
//
//                    if (notNotifyIds == null || !notNotifyIds.contains(chatUsename)) {
//                        return true;
//                    } else {
//                        return false;
//                    }
//                }
//            }
//        });
//        //set emoji icon provider
//        easeUI.setEmojiconInfoProvider(new EaseEmojiconInfoProvider() {
//
//            @Override
//            public EmojiconEntity getEmojiconInfo(String emojiconIdentityCode) {
//                EaseEmojiconGroupEntity data = EmojiconExampleGroupData.getData();
//                for(EmojiconEntity emojicon : data.getEmojiconList()){
//                    if(emojicon.getIdentityCode().equals(emojiconIdentityCode)){
//                        return emojicon;
//                    }
//                }
//                return null;
//            }
//
//            @Override
//            public Map<String, Object> getTextEmojiconMapping() {
//                return null;
//            }
//        });
//
//        //set notification options, will use default if you don't set it
//        easeUI.getNotifier().setNotificationInfoProvider(new EaseNotificationInfoProvider() {
//
//            @Override
//            public String getTitle(EMMessage message) {
//                //you can update title here
//                return null;
//            }
//
//            @Override
//            public int getSmallIcon(EMMessage message) {
//                //you can update icon here
//                return 0;
//            }
//
//            @Override
//            public String getDisplayedText(EMMessage message) {
//                // be used on notification bar, different text according the message type.
//                String ticker = EaseCommonUtils.getMessageDigest(message, appContext);
//                if(message.getType() == EMMessage.Type.TXT){
//                    ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
//                }
//                EaseUser user = getUserInfo(message.getFrom());
//                if(user != null){
//                    if(EaseAtMessageHelper.get().isAtMeMsg(message)){
//                        return String.format(appContext.getString(R.string.at_your_in_group), user.getNick());
//                    }
//                    return user.getNick() + ": " + ticker;
//                }else{
//                    if(EaseAtMessageHelper.get().isAtMeMsg(message)){
//                        return String.format(appContext.getString(R.string.at_your_in_group), message.getFrom());
//                    }
//                    return message.getFrom() + ": " + ticker;
//                }
//            }
//
//            @Override
//            public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {
//                // here you can customize the text.
//                // return fromUsersNum + "contacts send " + messageNum + "messages to you";
//                return null;
//            }
//
//            @Override
//            public Intent getLaunchIntent(EMMessage message) {
//                // you can set what activity you want display when user click the notification
//                Intent intent = new Intent(appContext, ChatActivity.class);
//                // open calling activity if there is call
//                if(isVideoCalling){
//                    intent = new Intent(appContext, VideoCallActivity.class);
//                }else if(isVoiceCalling){
//                    intent = new Intent(appContext, VoiceCallActivity.class);
//                }else{
//                    EMMessage.ChatType chatType = message.getChatType();
//                    if (chatType == EMMessage.ChatType.Chat) { // single chat message
//                        intent.putExtra("userId", message.getFrom());
//                        intent.putExtra("chatType", Constant.CHATTYPE_SINGLE);
//                    } else { // group chat message
//                        // message.getTo() is the group id
//                        intent.putExtra("userId", message.getTo());
//                        if(chatType == EMMessage.ChatType.GroupChat){
//                            intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
//                        }else{
//                            intent.putExtra("chatType", Constant.CHATTYPE_CHATROOM);
//                        }
//
//                    }
//                }
//                return intent;
//            }
//        });
//    }


    EMConnectionListener connectionListener;
//    HashMap event = new HashMap();

    /**
     * set global listener
     */
    protected void setGlobalListeners() {
        syncGroupsListeners = new ArrayList<DataSyncListener>();
        syncContactsListeners = new ArrayList<DataSyncListener>();
        syncBlackListListeners = new ArrayList<DataSyncListener>();

//        isGroupsSyncedWithServer = demoModel.isGroupsSynced();
//        isContactsSyncedWithServer = demoModel.isContactSynced();
//        isBlackListSyncedWithServer = demoModel.isBacklistSynced();

        // create the global connection listener
        connectionListener = new EMConnectionListener() {
            @Override
            public void onDisconnected(int error) {
//                event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
                if (error == EMError.USER_REMOVED) {
                    LogUtil.d(TAG, "wubaojie>>>" + "onDisconnected: " + "环信用户已经被移除");
                    onCurrentAccountRemoved();
                } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                    LogUtil.d(TAG, "wubaojie>>>" + "onDisconnected: " + "环信帐号在其他设备登录");
                    onConnectionConflict();
                } else {
                    if (AppUtils.isConnected(appContext)) {
                        LogUtil.d(TAG, "wubaojie>>>" + "onDisconnected: " + "连接不到环信聊天服务器");
//                        event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.HUANXIN_NET_OVERLOAD);
//                        EventBus.getDefault().post(event);
                    } else {
                        LogUtil.d(TAG, "wubaojie>>>" + "onDisconnected: " + "环信:当前网络不可用");
//                        event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.HUANXIN_NET_OFFLINE);
//                        EventBus.getDefault().post(event);
                    }
                }
            }

            @Override
            public void onConnected() {
//                event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
//                event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.HUANXIN_NET_RECONNECT);
//                EventBus.getDefault().post(event);
                LogUtil.d(TAG, "wubaojie>>>" + "onConnected: " + "环信成功连接");
                // in case group and contact were already synced, we supposed to notify sdk we are ready to receive
                // the events
                if (isGroupsSyncedWithServer && isContactsSyncedWithServer) {
                    EMLog.d(TAG, "group and contact already synced with servre");
                } else {
                    if (!isGroupsSyncedWithServer) {
                        asyncFetchGroupsFromServer(null);
                    }

                    if (!isContactsSyncedWithServer) {
                        asyncFetchContactsFromServer(null);
                    }

                    if (!isBlackListSyncedWithServer) {
                        asyncFetchBlackListFromServer(null);
                    }
                }
            }
        };

        IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager()
                .getIncomingCallBroadcastAction());
        if (callReceiver == null) {
            callReceiver = new CallReceiver();
        }
        //register incoming call receiver
        appContext.registerReceiver(callReceiver, callFilter);

        //register connection listener
        EMClient.getInstance().addConnectionListener(connectionListener);
        //register group and contact event listener
//        registerGroupAndContactListener();
        //register message event listener
//        registerMessageListener();
        EMClient.getInstance().chatManager().addMessageListener(new HxMessageListener());

    }

    /**
     * if ever logged in
     *
     * @return
     */
    public boolean isLoggedIn() {
        return EMClient.getInstance().isLoggedInBefore();
    }

    /**
     * register group and contact listener, you need register when login
     */
    public void registerGroupAndContactListener() {
//        if (!isGroupAndContactListenerRegisted) {
//            EMClient.getInstance().groupManager().addGroupChangeListener(new MyGroupChangeListener());
//            EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
//            isGroupAndContactListenerRegisted = true;
//        }

    }

//    /**
//     * group change listener
//     */
//    class MyGroupChangeListener implements EMGroupChangeListener {
//
//        @Override
//        public void onInvitationReceived(String s, String s1, String s2, String s3) {
//
//        }
//
//        @Override
//        public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {
//
//        }
//
//        @Override
//        public void onRequestToJoinAccepted(String s, String s1, String s2) {
//
//        }
//
//        @Override
//        public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {
//
//        }
//
//        @Override
//        public void onInvitationAccepted(String s, String s1, String s2) {
//
//        }
//
//        @Override
//        public void onInvitationDeclined(String s, String s1, String s2) {
//
//        }
//
//        @Override
//        public void onUserRemoved(String s, String s1) {
//
//        }
//
//        @Override
//        public void onGroupDestroyed(String s, String s1) {
//
//        }
//
//        @Override
//        public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {
//
//        }
//
//        @Override
//        public void onMuteListAdded(String s, List<String> list, long l) {
//
//        }
//
//        @Override
//        public void onMuteListRemoved(String s, List<String> list) {
//
//        }
//
//        @Override
//        public void onAdminAdded(String s, String s1) {
//
//        }
//
//        @Override
//        public void onAdminRemoved(String s, String s1) {
//
//        }
//
//        @Override
//        public void onOwnerChanged(String s, String s1, String s2) {
//
//        }
//
//        @Override
//        public void onMemberJoined(String s, String s1) {
//
//        }
//
//        @Override
//        public void onMemberExited(String s, String s1) {
//
//        }
//
//        @Override
//        public void onAnnouncementChanged(String s, String s1) {
//
//        }
//
//        @Override
//        public void onSharedFileAdded(String s, EMMucSharedFile emMucSharedFile) {
//
//        }
//
//        @Override
//        public void onSharedFileDeleted(String s, String s1) {
//
//        }
//    }
//
//
//
//    /***
//     * 好友变化listener
//     */
//    public class MyContactListener implements EMContactListener {
//
//        @Override
//        public void onContactAdded(String s) {
//
//        }
//
//        @Override
//        public void onContactDeleted(String s) {
//
//        }
//
//        @Override
//        public void onContactInvited(String s, String s1) {
//
//        }
//
//        @Override
//        public void onFriendRequestAccepted(String s) {
//
//        }
//
//        @Override
//        public void onFriendRequestDeclined(String s) {
//
//        }
//    }

//    /**
//     * save and notify invitation message
//     * @param msg
//     */
//    private void notifyNewInviteMessage(InviteMessage msg){
//        if(inviteMessgeDao == null){
//            inviteMessgeDao = new InviteMessgeDao(appContext);
//        }
//        inviteMessgeDao.saveMessage(msg);
//        //increase the unread message count
//        inviteMessgeDao.saveUnreadMessageCount(1);
//        // notify there is new message
//        getNotifier().vibrateAndPlayTone(null);
//    }

    /**
     * user has logged into another device
     */
    protected void onConnectionConflict() {
        Log.d(TAG, "onConnectionConflict() called");
        T.showShort(appContext, appContext.getResources().getString(R.string.account_login_other_device));
//        Intent intent = new Intent(appContext, MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra(Constant.ACCOUNT_CONFLICT, true);
//        appContext.startActivity(intent);
    }

    /**
     * account is removed
     */
    protected void onCurrentAccountRemoved() {
        Log.d(TAG, "onCurrentAccountRemoved() called");
//        Intent intent = new Intent(appContext, MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra(Constant.ACCOUNT_REMOVED, true);
//        appContext.startActivity(intent);
    }

//    private EaseUser getUserInfo(String username){
//        // To get instance of EaseUser, here we get it from the user list in memory
//        // You'd better cache it if you get it from your server
//        EaseUser user = null;
//        if(username.equals(EMClient.getInstance().getCurrentUser()))
//            return getUserProfileManager().getCurrentUserInfo();
//        user = getContactList().get(username);
//        if(user == null && getRobotList() != null){
//            user = getRobotList().get(username);
//        }
//
//        // if user is not in your contacts, set inital letter for him/her
//        if(user == null){
//            user = new EaseUser(username);
//            EaseCommonUtils.setUserInitialLetter(user);
//        }
//        return user;
//    }


//    /**
//     * Global listener
//     * If this event already handled by an activity, you don't need handle it again
//     * activityList.size() <= 0 means all activities already in background or not in Activity Stack
//     */
//    protected void registerMessageListener() {
//        messageListener = new EMMessageListener() {
//            private BroadcastReceiver broadCastReceiver = null;
//
//            @Override
//            public void onMessageReceived(List<EMMessage> messages) {
//                LogUtil.e(TAG, "wubaojie>>>messageSize : " + messages.size());
//                for (EMMessage message : messages) {
//                    LogUtil.e(TAG, "wubaojie>>>" + "onMessageReceived: \n" + message.toString());
//                    Notifier.getInstance().onNewMsg(message);
////                    if (EMMessage.ChatType.GroupChat == message.getChatType() || EMMessage.ChatType.ChatRoom ==
//// message.getChatType()) {
////                        //群聊
////                    } else if (message.getChatType() == EMMessage.ChatType.Chat) {
////                        //单聊
////
////                    }
//                    // in background, do not refresh UI, notify it in notification bar
////                    if(!easeUI.hasForegroundActivies()){
////                        getNotifier().onNewMsg(message);
////                    }
//                }
//            }
//
//            @Override
//            public void onCmdMessageReceived(List<EMMessage> messages) {
//                Log.d(TAG, "onCmdMessageReceived() called with: messages = [" + messages + "]");
//                for (EMMessage message : messages) {
//                    EMLog.d(TAG, "receive command message");
//                    //get message body
//                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
//                    final String action = cmdMsgBody.action();//获取自定义action
//                    //red packet code : 处理红包回执透传消息
////                    if(!easeUI.hasForegroundActivies()){
////                        if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)){
////                            RedPacketUtil.receiveRedPacketAckMessage(message);
////                            broadcastManager.sendBroadcast(new Intent(RedPacketConstant
//// .REFRESH_GROUP_RED_PACKET_ACTION));
////                        }
////                    }
//                    //end of red packet code
//                    //获取扩展属性 此处省略
//                    //maybe you need get extension of your message
//                    //message.getStringAttribute("");
//                    EMLog.d(TAG, String.format("Command：action:%s,message:%s", action, message.toString()));
//                }
//            }
//
//            @Override
//            public void onMessageReadAckReceived(List<EMMessage> messages) {
//                Log.d(TAG, "onMessageReadAckReceived() called with: messages = [" + messages + "]");
//            }
//
//            @Override
//            public void onMessageDeliveryAckReceived(List<EMMessage> message) {
//                Log.d(TAG, "onMessageDeliveryAckReceived() called with: message = [" + message + "]");
//            }
//
//            @Override
//            public void onMessageChanged(EMMessage message, Object change) {
//                Log.d(TAG, "onMessageChanged() called with: message = [" + message + "], change = [" + change + "]");
//            }
//        };
//
//        EMClient.getInstance().chatManager().addMessageListener(messageListener);
//    }


//    public void Login(String username, String password, EMCallBack callback) {
//        if (!Constants.ISHuanXinEnable) return;
//        //loginOut();
//        username = username.replace("-", "");
//        boolean islogin = hxSDKHelper.isLogined();
//        Log.v(tag, "Login>>>>" + username + " " + islogin);
//        if (islogin) return;
//        final String t_usname = username;
//        if (callback == null) {
//            callback = new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//
//                    Log.i(tag, "hx Login onSuccess >>>>>>>>>>>>>>:");
//                    // 登陆成功，保存用户名密码
//                    HuanXinManager.getIntance().setUserName(t_usname);
//                    try {
//                        // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
//                        // ** manually load all local groups and
//                        EMGroupManager.getInstance().loadAllGroups();
//                        EMChatManager.getInstance().loadAllConversations();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        return;
//                    }
//                    // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
//                    boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick
//                            (MyInfoUtil.getName(BaseApplication.mInstance).trim());
//                    if (!updatenick) {
//                        Log.e(tag, "update current user nick fail");
//                    }
//
//
//                }
//
//                @Override
//                public void onProgress(int arg0, String arg1) {
//                    // TODO Auto-generated method stub
//
//                }
//
//                @Override
//                public void onError(int arg0, String arg1) {
//                    Log.i(tag, "hx onError >>>>>>>>>>>>>>:");
//
//                }
//            };
//        }
//        EMChatManager.getInstance().login(username, password_temp, callback);
//    }


    public void login(String username, String password, EMCallBack callback) {
        Log.d(TAG, "login...");
        username = username.replace("-", "");
        LogUtil.d(username);
        LogUtil.d("isLoggedIn()>>" + isLoggedIn());
        if (isLoggedIn()) return;
        if (callback == null) {
            callback = new EMCallBack() {
                @Override
                public void onSuccess() {
                    Log.i(TAG, "hx login onSuccess >>>>>>>>>>>>>>:");
                    // ** manually load all local groups and conversation
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                }

                @Override
                public void onError(int i, final String s) {
                    Log.i(TAG, "hx login onError >>>>>>>>>>>>>>:");
                    Observable.create(new Observable.OnSubscribe<Object>() {
                        @Override
                        public void call(Subscriber<? super Object> subscriber) {
                            subscriber.onNext("");
                            subscriber.onCompleted();
                        }
                    }).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            throwable.printStackTrace();
                        }

                        @Override
                        public void onNext(Object result) {
                            Toast.makeText(appContext, "环信登录失败" + s, Toast.LENGTH_SHORT).show();
                        }
                    });

                }

                @Override
                public void onProgress(int i, String s) {
                    Log.i(TAG, "hx login onProgress >>>>>>>>>>>>>>:");
                }
            };
        }
        EMClient.getInstance().login(username, password_temp, callback);
    }

//        EMClient.getInstance().login(currentUsername, currentPassword, new EMCallBack() {
//            @Override
//            public void onSuccess() {
//                Log.d(TAG, "login: onSuccess");
//
//
//                // ** manually load all local groups and conversation
//                EMClient.getInstance().groupManager().loadAllGroups();
//                EMClient.getInstance().chatManager().loadAllConversations();
//
//                // update current user's display name for APNs
//                boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
//                        DemoApplication.currentUserNick.trim());
//                if (!updatenick) {
//                    Log.e("LoginActivity", "update current user nick fail");
//                }
//
//                if (!LoginActivity.this.isFinishing() && pd.isShowing()) {
//                    pd.dismiss();
//                }
//                // get user's info (this should be get from App's server or 3rd party service)
//                HuanXinHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
//
//                Intent intent = new Intent(LoginActivity.this,
//                        MainActivity.class);
//                startActivity(intent);
//
//                finish();
//            }

//            @Override
//            public void onProgress(int progress, String status) {
//                Log.d(TAG, "login: onProgress");
//            }
//
//            @Override
//            public void onError(final int code, final String message) {
//                Log.d(TAG, "login: onError: " + code);
//                if (!progressShow) {
//                    return;
//                }
//                runOnUiThread(new Runnable() {
//                    public void run() {
//                        pd.dismiss();
//                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
//                                Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//        });

    /**
     * logout
     *
     * @param unbindDeviceToken whether you need unbind your device token
     * @param callback          callback
     */
    public void logout(boolean unbindDeviceToken, final EMCallBack callback) {
        endCall();
        Log.d(TAG, "logout: " + unbindDeviceToken);
        EMClient.getInstance().logout(unbindDeviceToken, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.d(TAG, "logout: onSuccess");
                reset();
                if (callback != null) {
                    callback.onSuccess();
                }
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d(TAG, "logout: onProgress");
                if (callback != null) {
                    callback.onProgress(progress, status);
                }
            }

            @Override
            public void onError(int code, String error) {
                Log.d(TAG, "logout: onSuccess");
                reset();
                if (callback != null) {
                    callback.onError(code, error);
                }
            }
        });
    }

    /**
     * get instance of EaseNotifier
     * @return
     */
//    public EaseNotifier getNotifier(){
//        return easeUI.getNotifier();
//    }

//    public DemoModel getModel(){
//        return (DemoModel) demoModel;
//    }

//    /**
//     * update contact list
//     *
//     * @param contactList
//     */
//    public void setContactList(Map<String, EaseUser> aContactList) {
//        if(aContactList == null){
//            if (contactList != null) {
//                contactList.clear();
//            }
//            return;
//        }
//
//        contactList = aContactList;
//    }

    /**
     * save single contact
     */
//    public void saveContact(EaseUser user){
//        contactList.put(user.getUsername(), user);
//        demoModel.saveContact(user);
//    }

    /**
     * get contact list
     *
     * @return
     */
//    public Map<String, EaseUser> getContactList() {
//        if (isLoggedIn() && contactList == null) {
//            contactList = demoModel.getContactList();
//        }
//
//        // return a empty non-null object to avoid app crash
//        if(contactList == null){
//            return new Hashtable<String, EaseUser>();
//        }
//
//        return contactList;
//    }

    /**
     * set current username
     * @param username
     */
//    public void setCurrentUserName(String username){
//        this.username = username;
//        demoModel.setCurrentUserName(username);
//    }

    /**
     * get current user's id
     */
//    public String getCurrentUsernName(){
//        if(username == null){
//            username = demoModel.getCurrentUsernName();
//        }
//        return username;
//    }

//    public void setRobotList(Map<String, RobotUser> robotList) {
//        this.robotList = robotList;
//    }
//
//    public Map<String, RobotUser> getRobotList() {
//        if (isLoggedIn() && robotList == null) {
//            robotList = demoModel.getRobotList();
//        }
//        return robotList;
//    }

    /**
     * update user list to cache and database
     *
     * @param
     * @param
     */
//    public void updateContactList(List<EaseUser> contactInfoList) {
//        for (EaseUser u : contactInfoList) {
//            contactList.put(u.getUsername(), u);
//        }
//        ArrayList<EaseUser> mList = new ArrayList<EaseUser>();
//        mList.addAll(contactList.values());
//        demoModel.saveContactList(mList);
//    }

//    public UserProfileManager getUserProfileManager() {
//        if (userProManager == null) {
//            userProManager = new UserProfileManager();
//        }
//        return userProManager;
//    }

    void endCall() {
        try {
            EMClient.getInstance().callManager().endCall();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addSyncGroupListener(DataSyncListener listener) {
        if (listener == null) {
            return;
        }
        if (!syncGroupsListeners.contains(listener)) {
            syncGroupsListeners.add(listener);
        }
    }

    public void removeSyncGroupListener(DataSyncListener listener) {
        if (listener == null) {
            return;
        }
        if (syncGroupsListeners.contains(listener)) {
            syncGroupsListeners.remove(listener);
        }
    }

    public void addSyncContactListener(DataSyncListener listener) {
        if (listener == null) {
            return;
        }
        if (!syncContactsListeners.contains(listener)) {
            syncContactsListeners.add(listener);
        }
    }

    public void removeSyncContactListener(DataSyncListener listener) {
        if (listener == null) {
            return;
        }
        if (syncContactsListeners.contains(listener)) {
            syncContactsListeners.remove(listener);
        }
    }

    public void addSyncBlackListListener(DataSyncListener listener) {
        if (listener == null) {
            return;
        }
        if (!syncBlackListListeners.contains(listener)) {
            syncBlackListListeners.add(listener);
        }
    }

    public void removeSyncBlackListListener(DataSyncListener listener) {
        if (listener == null) {
            return;
        }
        if (syncBlackListListeners.contains(listener)) {
            syncBlackListListeners.remove(listener);
        }
    }

    /**
     * Get group list from server
     * This method will save the sync state
     *
     * @throws HyphenateException
     */
    public synchronized void asyncFetchGroupsFromServer(final EMCallBack callback) {
        if (isSyncingGroupsWithServer) {
            return;
        }

        isSyncingGroupsWithServer = true;

        new Thread() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().groupManager().getJoinedGroupsFromServer();

                    // in case that logout already before server returns, we should return immediately
                    if (!isLoggedIn()) {
                        isGroupsSyncedWithServer = false;
                        isSyncingGroupsWithServer = false;
                        noitifyGroupSyncListeners(false);
                        return;
                    }

//                    demoModel.setGroupsSynced(true);

                    isGroupsSyncedWithServer = true;
                    isSyncingGroupsWithServer = false;

                    //notify sync group list success
                    noitifyGroupSyncListeners(true);

                    if (callback != null) {
                        callback.onSuccess();
                    }
                } catch (HyphenateException e) {
//                    demoModel.setGroupsSynced(false);
                    isGroupsSyncedWithServer = false;
                    isSyncingGroupsWithServer = false;
                    noitifyGroupSyncListeners(false);
                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.toString());
                    }
                }

            }
        }.start();
    }

    public void noitifyGroupSyncListeners(boolean success) {
        for (DataSyncListener listener : syncGroupsListeners) {
            listener.onSyncComplete(success);
        }
    }

    public void asyncFetchContactsFromServer(final EMValueCallBack<List<String>> callback) {
        if (isSyncingContactsWithServer) {
            return;
        }

        isSyncingContactsWithServer = true;

        new Thread() {
            @Override
            public void run() {
                List<String> usernames = null;
                try {
                    usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                    // in case that logout already before server returns, we should return immediately
                    if (!isLoggedIn()) {
                        isContactsSyncedWithServer = false;
                        isSyncingContactsWithServer = false;
                        notifyContactsSyncListener(false);
                        return;
                    }

//                    Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
//                    for (String username : usernames) {
//                        EaseUser user = new EaseUser(username);
//                        EaseCommonUtils.setUserInitialLetter(user);
//                        userlist.put(username, user);
//                    }
//                    // save the contact list to cache
//                    getContactList().clear();
//                    getContactList().putAll(userlist);
//                    // save the contact list to database
//                    UserDao dao = new UserDao(appContext);
//                    List<EaseUser> users = new ArrayList<EaseUser>(userlist.values());
//                    dao.saveContactList(users);
//
//                    demoModel.setContactSynced(true);
                    EMLog.d(TAG, "set contact syn status to true");

                    isContactsSyncedWithServer = true;
                    isSyncingContactsWithServer = false;

                    //notify sync success
                    notifyContactsSyncListener(true);

//                    getUserProfileManager().asyncFetchContactInfosFromServer(usernames,new
// EMValueCallBack<List<EaseUser>>() {
//
//                        @Override
//                        public void onSuccess(List<EaseUser> uList) {
//                            updateContactList(uList);
//                            getUserProfileManager().notifyContactInfosSyncListener(true);
//                        }
//
//                        @Override
//                        public void onError(int error, String errorMsg) {
//                        }
//                    });
                    if (callback != null) {
                        callback.onSuccess(usernames);
                    }
                } catch (HyphenateException e) {
//                    demoModel.setContactSynced(false);
                    isContactsSyncedWithServer = false;
                    isSyncingContactsWithServer = false;
                    notifyContactsSyncListener(false);
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.toString());
                    }
                }

            }
        }.start();
    }

    public void notifyContactsSyncListener(boolean success) {
        for (DataSyncListener listener : syncContactsListeners) {
            listener.onSyncComplete(success);
        }
    }

    public void asyncFetchBlackListFromServer(final EMValueCallBack<List<String>> callback) {

        if (isSyncingBlackListWithServer) {
            return;
        }

        isSyncingBlackListWithServer = true;

        new Thread() {
            @Override
            public void run() {
                try {
                    List<String> usernames = EMClient.getInstance().contactManager().getBlackListFromServer();

                    // in case that logout already before server returns, we should return immediately
                    if (!isLoggedIn()) {
                        isBlackListSyncedWithServer = false;
                        isSyncingBlackListWithServer = false;
                        notifyBlackListSyncListener(false);
                        return;
                    }

//                    demoModel.setBlacklistSynced(true);

                    isBlackListSyncedWithServer = true;
                    isSyncingBlackListWithServer = false;

                    notifyBlackListSyncListener(true);
                    if (callback != null) {
                        callback.onSuccess(usernames);
                    }
                } catch (HyphenateException e) {
//                    demoModel.setBlacklistSynced(false);

                    isBlackListSyncedWithServer = false;
                    isSyncingBlackListWithServer = true;
                    e.printStackTrace();

                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.toString());
                    }
                }

            }
        }.start();
    }

    public void notifyBlackListSyncListener(boolean success) {
        for (DataSyncListener listener : syncBlackListListeners) {
            listener.onSyncComplete(success);
        }
    }

    public boolean isSyncingGroupsWithServer() {
        return isSyncingGroupsWithServer;
    }

    public boolean isSyncingContactsWithServer() {
        return isSyncingContactsWithServer;
    }

    public boolean isSyncingBlackListWithServer() {
        return isSyncingBlackListWithServer;
    }

    public boolean isGroupsSyncedWithServer() {
        return isGroupsSyncedWithServer;
    }

    public boolean isContactsSyncedWithServer() {
        return isContactsSyncedWithServer;
    }

    public boolean isBlackListSyncedWithServer() {
        return isBlackListSyncedWithServer;
    }

    synchronized void reset() {
        isSyncingGroupsWithServer = false;
        isSyncingContactsWithServer = false;
        isSyncingBlackListWithServer = false;

//        demoModel.setGroupsSynced(false);
//        demoModel.setContactSynced(false);
//        demoModel.setBlacklistSynced(false);

        isGroupsSyncedWithServer = false;
        isContactsSyncedWithServer = false;
        isBlackListSyncedWithServer = false;

//        isGroupAndContactListenerRegisted = false;

//        setContactList(null);
//        setRobotList(null);
//        getUserProfileManager().reset();
//        DemoDBManager.getInstance().closeDB();
        WNXDBManager.getInstance().closeDB();
    }

//    /**
//     * new message options provider
//     */
//    public interface EaseSettingsProvider {
//        boolean isMsgNotifyAllowed(EMMessage message);
//
//        boolean isMsgSoundAllowed(EMMessage message);
//
//        boolean isMsgVibrateAllowed(EMMessage message);
//
//        boolean isSpeakerOpened();
//    }
//    public void pushActivity(Activity activity) {
//        easeUI.pushActivity(activity);
//    }
//
//    public void popActivity(Activity activity) {
//        easeUI.popActivity(activity);
//    }

}
